﻿using System;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Xml;

namespace Painter.Component
{
    public static class XmlManage
    {
        static object LOCK = new object();
        /// <summary>
        /// 获取指定xml文件中的键值
        /// </summary>
        /// <param name="nodeName"></param>
        ///<param name="key"></param> 
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        public static string GetKeyValue(string nodeName, string key, string xmlPath)
        {

            XmlNodeList xNode = GetXmlNodes(nodeName, xmlPath);
            if (xNode.Count > 0)
            {
                return xNode[0].Attributes[key].Value;
            }
            return "";
        }

        /// <summary>
        /// 获取指定xml文件中的键值
        /// </summary>
        /// <param name="nodeName"></param>
        ///<param name="key"></param> 
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        public static string GetKeyValue(string nodeName, string xmlStr)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlStr);
            XmlNode xNode = xmlDoc.SelectSingleNode(nodeName);
            return xNode.Value;
        }

        /// <summary>
        /// 加载xml节点内容
        /// </summary>
        /// <param name="nodeName"></param>
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        public static XmlNodeList GetXmlNodes(string nodeName, string xmlPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + xmlPath);
            return xmlDoc.SelectNodes("//" + nodeName);
        }


        #region SetConfiguration
        /// <summary>
        /// 标识当前应用是否为 Web 应用
        /// </summary>
        private static readonly bool isWeb = CheckWhetherIsWeb();
        /// <summary>
        /// 设置appSetting的值
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SetConfiguration(string key, string value, bool clearFlag = false)
        {
            lock (LOCK)
            {
                if (!isWeb)
                {
                    string filePath = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName + ".config";

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(filePath);
                    XmlNode node = xmlDoc.DocumentElement.SelectSingleNode("appSettings");
                    XmlNode keyNode = node.SelectSingleNode("add[@key='" + key + "']");
                    if (keyNode == null)
                    {
                        keyNode = xmlDoc.CreateNode(XmlNodeType.Element, "add", null);
                        XmlAttribute attribute = xmlDoc.CreateAttribute("key", null);
                        attribute.Value = key;
                        keyNode.Attributes.Append(attribute);
                        attribute = xmlDoc.CreateAttribute("value", null);
                        attribute.Value = value;
                        keyNode.Attributes.Append(attribute);
                        node.AppendChild(keyNode);
                    }

                    if (!clearFlag)
                    {
                        //赋值并保存
                        keyNode.Attributes["value"].Value = value;
                    }
                    else
                    {
                        keyNode.Attributes["value"].Value = "";
                    }

                    xmlDoc.Save(filePath);
                }
                else
                {
                    Configuration configuration = null;                 //Configuration对象
                    AppSettingsSection appSection = null;               //AppSection对象 
                    try
                    {
                        configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

                    }
                    catch
                    {
                        configuration = WebConfigurationManager.OpenWebConfiguration(null);

                    }
                    //取得AppSetting节
                    appSection = configuration.AppSettings;
                    if (!clearFlag)
                    {
                        //赋值并保存
                        appSection.Settings[key].Value = value;
                    }
                    else
                    {
                        appSection.Settings[key].Value = "";
                    }
                    configuration.Save();
                }
            }
        }

        /// <summary>
        /// 获取appsetting的值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static string GetConfigurationValue(string key)
        {
            if (!isWeb)
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName + ".config";

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);
                XmlNode node = xmlDoc.DocumentElement.SelectSingleNode("appSettings");
                XmlNode keyNode = node.SelectSingleNode("add[@key='" + key + "']");
                if (keyNode != null)
                {
                    return keyNode.Attributes["value"].Value;
                }
                return string.Empty;
            }
            else
            {
                Configuration configuration = null;                 //Configuration对象
                //AppSettingsSection appSection = null;               //AppSection对象 
                try
                {
                    configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

                }
                catch
                {
                    configuration = WebConfigurationManager.OpenWebConfiguration(null);

                }

                return ConfigurationManager.AppSettings.AllKeys.Contains(key) ? ConfigurationManager.AppSettings[key].ToString() : "";
            }
        }

        /// <summary>
        /// 判断当前应用是否为 Web 应用的 Helper 方法 （非官方方法）
        /// </summary>
        /// <returns></returns>
        private static bool CheckWhetherIsWeb()
        {
            bool result = false;
            AppDomain domain = AppDomain.CurrentDomain;
            try
            {
                if (domain.ShadowCopyFiles)
                    result = (HttpContext.Current.GetType() != null);
            }
            catch (System.Exception) { }
            return result;
        }
        #endregion
    }
}
